//
//  commentview.m
//  WuyouTang
//
//  Created by 王敏欣 on 2017/8/5.
//  Copyright © 2017年 cat. All rights reserved.
//
#import "commentview.h"
#import "commentModel.h"
#import "commCell.h"
#import "XHVoiceRecordHUD.h"
#import "XHVoiceRecordHelper.h"
#import "commDetailCell.h"
#import "SelPeopleV.h"
@interface commentview ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,commCellDelegate,UIGestureRecognizerDelegate>
{
    int count;//下拉次数
    MJRefreshBackNormalFooter *footer;
    int ispush;
    
    BOOL isReply;//判断是否是回复
    UILabel *tableviewLine;
    UIView *tableheader;

    CGFloat _oldOffset;
    
    NSIndexPath *_needScorllToIndexPath;   //需要滚动到
    BOOL _needScroll;
    commCell *_currentCell;
    BOOL isLandScreen;
}
@property(nonatomic,strong)UILabel *allCommentLabels;//显示全部评论
@property(nonatomic,copy)NSString *videoid;//视频id
@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSMutableArray *itemsarray;//评论列表
//@property(nonatomic,strong)NSMutableArray *modelarray;//评论模型
@property(nonatomic,copy)NSString *parentid;//回复的评论ID
@property(nonatomic,copy)NSString *commentid;//回复的评论commentid
@property(nonatomic,copy)NSString *touid;//回复的评论UID
@property(nonatomic,copy)NSString *hostid;//发布视频的人的id

@property (nonatomic,strong) AVPlayer *voicePlayer;
@property (nonatomic,assign) BOOL isPlaying;
@property (nonatomic,strong) commCell *voiceCell;
@property (nonatomic,strong) commDetailCell *detailVoiceCell;
@property (nonatomic,assign) BOOL isDetailPlay;
//监听播放起状态的监听者
@property (nonatomic ,strong) id playbackTimeObserver;


@end
@implementation commentview
-(void)dealloc{
    NSLog(@"dealloc");
}
- (void)reloadCurCell:(commentModel *)model andIndex:(NSIndexPath *)curIndex andReplist:(NSArray *)list needRefresh:(BOOL)needRefresh{
    for (int i = 0; i < _itemsarray.count; i++) {
        NSMutableDictionary *muDic = _itemsarray[i];
        if ([minstr([muDic valueForKey:@"id"]) isEqual:model.parentid]) {
            [muDic setObject:list forKey:@"replylist"];
            [muDic setObject:model.replys forKey:@"replys"];
//            mol.replyList = list;
//            NSLog(@"-------%@",mol.replyList);
////            [_modelarray removeObject:mol];
//            [_modelarray replaceObjectAtIndex:i withObject:model];
            break;
        }
    }
    if (needRefresh) {
        [_tableview reloadRowsAtIndexPaths:@[curIndex] withRowAnimation:UITableViewRowAnimationNone];
    }
}
//每次点击 获取最新评论列表
-(void)reloaddata:(NSString *)from{
    
    count+=1;
    _commentTool.textField.text = @"";
    _commentTool.textField.placeholder = YZMsg(@"说点什么吧~");
    NSString *url = [NSString stringWithFormat:@"Video.getComments&videoid=%@&p=%d&uid=%@",_videoid,count,[Config getOwnID]];
    
    YBWeakSelf;
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        [weakSelf.tableview.mj_header endRefreshing];
        if (code == 0) {
            //隐藏评论加载中
            [PublicView hideCommenting:weakSelf.tableview];
            NSDictionary *infoDic = [info firstObject];
            NSArray *commentlist = [infoDic valueForKey:@"commentlist"];
            
            int allcomments = [[NSString stringWithFormat:@"%@",[infoDic valueForKey:@"comments"]] intValue];
            weakSelf.allCommentLabels.text = [NSString stringWithFormat:@"%d %@",allcomments,YZMsg(@"评论")];
            self.talkCount([NSString stringWithFormat:@"%@",[infoDic valueForKey:@"comments"]] );
            if (count == 1) {
                [_itemsarray removeAllObjects];
            }
            for (NSDictionary *dic in commentlist) {
                NSMutableDictionary *mudic = [dic mutableCopy];
                [_itemsarray addObject:mudic];
            }
            if (_itemsarray.count == 0) {
                [PublicView showTextNoData:_tableview text1:@"" text2:YZMsg(@"暂无评论，快来抢沙发吧") centerY:0.8];
            }else{
                [PublicView hiddenTextNoData:_tableview];
            }
            if (commentlist.count == 0) {
                [weakSelf.tableview.mj_footer endRefreshingWithNoMoreData];
            }else{
                [weakSelf.tableview.mj_footer endRefreshing];
            }
            [weakSelf.tableview reloadData];
            if (_needScroll) {
                _needScroll = NO;
                //滚动
                if (_itemsarray.count > _needScorllToIndexPath.row) {
                    [_tableview scrollToRowAtIndexPath:_needScorllToIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
                }
            }
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
    
    
}
-(instancetype)initWithFrame:(CGRect)frame hide:(commectblock)hide andvideoid:(NSString *)videoid andhostid:(NSString *)hostids count:(int)allcomments talkCount:(commectblock)talk detail:(commectblock)detail youke:(commectblock)youkedenglu andFrom:(NSString *)from{
    self = [super initWithFrame:frame];
    if (self) {

        _needScroll = NO;
        _needScorllToIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        _fromWhere = from;
        _oldOffset = 0;
         ispush = 0;//判断发消息的时候 数组滚动最上面
         count = 0;//上拉加载次数
        _parentid = @"0";
        _commentid = @"0";
        isReply = NO;//判断回复
        self.talkCount = talk;
        self.hide = hide;//点击隐藏事件
        _videoid = videoid;//获取视频id
        _hostid = hostids;
        _touid = hostids;
        _pushDetail = detail;
        _youkedenglu = youkedenglu;
        _itemsarray = [NSMutableArray array];
//        _modelarray = [NSMutableArray array];

        
        tableheader = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height*0.3 , _window_width,50)];
        if ([from isEqual:@"消息事件"]) {
            tableheader.y = 20+statusbarHeight;
        }
        tableheader.layer.masksToBounds = YES;
        tableheader.layer.cornerRadius = 10;
        tableheader.backgroundColor = RGB(245, 245, 245);
        
        //显示评论的数量
        _allCommentLabels = [[UILabel alloc]initWithFrame:CGRectMake(20,0,_window_width/2,50)];
        _allCommentLabels.textColor = GrayText;
        _allCommentLabels.text = [NSString stringWithFormat:@"%d %@",allcomments,YZMsg(@"评论")];
        _allCommentLabels.font = [UIFont systemFontOfSize:15];
        [tableheader addSubview:_allCommentLabels];
        
        //关闭按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(_window_width - 45,5,40,40);
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        btn.imageEdgeInsets = UIEdgeInsetsMake(12.5,12.5,12.5,12.5);
        [btn setImage:[UIImage imageNamed:@"gray_close"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(dissmiss) forControlEvents:UIControlEventTouchUpInside];
        [tableheader addSubview:btn];
        
        //tableview顶部横线 和 顶部 view分割开
        UILabel *liness = [[UILabel alloc]initWithFrame:CGRectMake(0,49,_window_width,1)];
        liness.backgroundColor = RGB(235, 235, 235);
        [tableheader addSubview:liness];
        [self addSubview:tableheader];
        
        UIView *headerBg = [[UIView alloc]init];
        headerBg.backgroundColor = tableheader.backgroundColor;
        [self addSubview:headerBg];
        [self sendSubviewToBack:headerBg];
        [headerBg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.centerX.height.equalTo(tableheader);
            make.top.equalTo(tableheader.mas_centerY);
        }];
        
        CGRect tabFrame ;
        if ([from isEqual:@"消息事件"]) {
            tabFrame = CGRectMake(0, 20+statusbarHeight+50, _window_width, _window_height-ShowDiff-20-statusbarHeight-50);
        }else {
            tabFrame = CGRectMake(0, _window_height*0.3+50, _window_width, _window_height*0.7 - 50-ShowDiff-50);
        }
        _tableview = [[UITableView alloc]initWithFrame:tabFrame];
        _tableview.delegate   = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor = UIColor.whiteColor;
        _tableview.layer.masksToBounds = YES;
        _tableview.showsVerticalScrollIndicator = NO;
        _tableview.estimatedRowHeight = 120.0;
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
//        _tableview.layer.masksToBounds = YES;
//        _tableview.layer.cornerRadius = 10;
        
        UIView *spaceView = [[UIView alloc]initWithFrame:CGRectMake(0, _tableview.bottom-12, _window_width, 15)];
        spaceView.backgroundColor = _tableview.backgroundColor;
        [self addSubview:spaceView];
        [self addSubview:_tableview];
        [self addSubview:self.commentTool];
        
        //tableview顶部横线 和 顶部 view分割开
        tableviewLine = [[UILabel alloc]initWithFrame:CGRectMake(0, _window_height*0.3 + 49,_window_width,1)];
        tableviewLine.backgroundColor = Line_Cor;//[UIColor colorWithRed:198/255.0 green:198/255.0 blue:198/255.0 alpha:1];
        //[self addSubview:tableviewLine];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

//        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeBottomTool) name:@"landForTurn" object:nil];
        //评论加载中
        [PublicView showCommenting:_tableview];
        
        [self reloaddata:from];
        
        _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            count = 0;
            [self reloaddata:from];
        }];
        
        footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloaddata:)];
        footer.backgroundColor = UIColor.clearColor;
        [footer setTitle:YZMsg(@"评论加载中...") forState:MJRefreshStateRefreshing];
        [footer setTitle:@"" forState:MJRefreshStateNoMoreData];//YZMsg(@"没有更多了哦~")
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        footer.stateLabel.font = [UIFont systemFontOfSize:15.0f];
        self.tableview.mj_footer = footer;
        
        //commectdetails 页面传过来的 点赞
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload:) name:@"likesnums" object:nil];
        //commectdetails 页面传过来的 回复总数
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadcomments:) name:@"commentnums" object:nil];
        
        //点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dissmiss)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        //长按手势--【不要添加代理】
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [_tableview addGestureRecognizer:longPress];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(goCenterNot:) name:@"goCenterNot" object:nil];
        
    }
    return self;
}
-(void)resetFream{
    isLandScreen = YES;
    tableheader.frame = CGRectMake(0, 0 , self.width,50);
    if(IS_BIG_SCREEN){
        if(IS_IPHONE_X){
            _tableview.frame = CGRectMake(0, tableheader.bottom, self.width, self.width-50);
        }else{
            _tableview.frame = CGRectMake(0, tableheader.bottom, self.width, self.width+20);
        }
    }else{
        _tableview.frame = CGRectMake(0, tableheader.bottom, self.width, self.width-50);
    }
    _commentTool.voiceBtn.hidden = YES;
    _commentTool.faceBtn.hidden = YES;
    _commentTool.textField.frame =CGRectMake(10,8, tableheader.width-30, 34);
    _commentTool.tv_bg.frame =_commentTool.textField.frame;
    if (_commentTool.emojiV) {
        [_commentTool.emojiV removeFromSuperview];
    }
    UIButton *closeBtn = [UIButton buttonWithType:0];
    closeBtn.frame = CGRectMake(tableheader.width-50, 10, 30, 30);
    [closeBtn setImage:[UIImage imageNamed:@"standardClose"] forState:0];
    [closeBtn addTarget:self action:@selector(closeBtnClikc) forControlEvents:UIControlEventTouchUpInside];
    [tableheader addSubview:closeBtn];
}
//-(void)closeBottomTool{
//    [_commentTool hiddenEmojiOrKeyBoard];
//}
-(void)closeBtnClikc{
    if(self.closeEvent){
        self.closeEvent();
    }
}
-(void)goCenterNot:(NSNotification*)noti {
    int isGo = [minstr(noti.object) intValue];
    if (self.goCenterEvent) {
        self.goCenterEvent(isGo);
    }
}
-(void)longPress:(UILongPressGestureRecognizer*)longPressGesture {
    if (_itemsarray.count <= 0) {
        return;
    }
    if ([_commentTool.textField isFirstResponder]) {
        [_commentTool.textField resignFirstResponder];
        return;
    }
    commCell *cell;
    if (longPressGesture.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [longPressGesture locationInView:_tableview];
        NSIndexPath *currentIndexPath = [_tableview indexPathForRowAtPoint:point];
        if (currentIndexPath) {
            cell = [_tableview cellForRowAtIndexPath:currentIndexPath];
        }
        cell.longPressView.backgroundColor = RGB_COLOR(@"#ffffff", 0.1);
        [self showActionSheet:currentIndexPath model:cell.model];
    }
    if (longPressGesture.state == UIGestureRecognizerStateChanged || longPressGesture.state == UIGestureRecognizerStateEnded) {
        CGPoint point = [longPressGesture locationInView:_tableview];
        NSIndexPath *currentIndexPath = [_tableview indexPathForRowAtPoint:point];
        if (currentIndexPath) {
            cell = [_tableview cellForRowAtIndexPath:currentIndexPath];
        }
        cell.longPressView.backgroundColor = UIColor.clearColor;
    }
    
}
-(void)showActionSheet:(NSIndexPath*)indexPath model:(commentModel *)cModel{
    
    if ([[Config getOwnID] intValue] <= 0) {
        [self needLogin];
        return;
    }
    
    NSDictionary *subdic = _itemsarray[indexPath.row];
    NSDictionary *userinfo = [subdic valueForKey:@"userinfo"];
    BOOL isVoice = [cModel.isvoice boolValue];
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
    if (!isVoice) {
        [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"复制") complete:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = [NSString stringWithFormat:@"@%@:%@",cModel.user_nickname,cModel.content];
                [MBProgressHUD showPop:YZMsg(@"复制成功")];
            });
        }];
    }
    BOOL haveDel = NO;
    if ([_hostid isEqual:[Config getOwnID]] || [minstr([userinfo valueForKey:@"id"]) isEqual:[Config getOwnID]]) {
        haveDel = YES;
        [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"删除") complete:^{
            [weakSelf delComments:subdic index:indexPath];
        }];
    }
    if (!isVoice || haveDel) {
        [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
        }];
//        [sheet showSheet];
        [sheet showLandscapeSheet:self];
    }
    
}
#pragma mark - 删除评论接口
-(void)delComments:(NSDictionary *)subdic index:(NSIndexPath *)indexPath{
    NSString *commentid = minstr([subdic valueForKey:@"id"]);
    NSDictionary *userinfo = [subdic valueForKey:@"userinfo"];
    NSString *commentUid = minstr([userinfo valueForKey:@"id"]);
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:@"Video.delComments" Dic:@{@"videoid":_videoid,@"commentid":commentid,@"commentuid":commentUid} Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:msg];
        if (code == 0) {
            count = 0;
            _needScroll = YES;
            int row = ((int)indexPath.row-1)>0?((int)indexPath.row-1):0;
            _needScorllToIndexPath = [NSIndexPath indexPathForRow:row inSection:0];;
            [self reloaddata:_fromWhere];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isDescendantOfView:_tableview] ||
        [touch.view isDescendantOfView:_commentTool] ||
        [touch.view isDescendantOfView:_commentTool.selV]||
        [touch.view isDescendantOfView:_commentTool.emojiV]||
        [touch.view isDescendantOfView:tableheader]) {
        return NO;
    }
    return YES;
}
-(void)dissmiss{
    if (self.mutedBlock) {
        self.mutedBlock(@"0");
    }

    _isPlaying = NO;
    if (_voicePlayer) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_voicePlayer.currentItem];
        [_voicePlayer removeTimeObserver:self.playbackTimeObserver];
        [_voicePlayer removeObserver:self forKeyPath:@"status"];
        [_voicePlayer pause];
        _voicePlayer = nil;
    }
    _isClickCloseBtn = YES;
    self.hide(@"1");
    [self endEditing:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [self.tableview deselectRowAtIndexPath:indexPath animated:NO];
    
    if ([[Config getOwnID] intValue] <= 0) {
        [self needLogin];
        return;
    }
    
    NSDictionary *subdic = _itemsarray[indexPath.row];
    NSDictionary *userinfo = [subdic valueForKey:@"userinfo"];
    _needScorllToIndexPath = indexPath;
    _currentCell = (commCell*)[tableView cellForRowAtIndexPath:indexPath];
   
    _touid = [NSString stringWithFormat:@"%@",[userinfo valueForKey:@"id"]];
    //20-6-28确定不能回复自己且不给提示
    if ([_touid isEqual:[Config getOwnID]]) {
        //[MBProgressHUD showPop:@"不能回复自己"];
        return;
    }

    if (_commentTool.voiceBtn.selected == NO) {
        [_commentTool.textField becomeFirstResponder];
    }
    NSString *path = [NSString stringWithFormat:@"%@:%@",YZMsg(@"回复给"),[userinfo valueForKey:@"user_nickname"]];
    _commentTool.textField.placeholder = path;
    _parentid = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"id"]];
    _commentid = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"commentid"]];
    isReply = YES;
    [_commentTool.voiceRecodeBtn setTitle:path forState:UIControlStateNormal];
    [_commentTool.voiceRecodeBtn setTitle:path forState:UIControlStateHighlighted];

}
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    commentModel *model = _modelarray[indexPath.row];
//    return model.rowH;
//}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemsarray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableview deselectRowAtIndexPath:indexPath animated:NO];
    commCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commCELL"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"commCell" owner:nil options:nil] lastObject];
    }
    cell.authorID = _hostid;
    cell.videoid = _videoid;
    cell.model = [[commentModel alloc]initWithDictionary:_itemsarray[indexPath.row]];
    cell.delegate = self;
    cell.curIndex = indexPath;
    [cell showLandscapeSuper:self];
    cell.backgroundColor = UIColor.whiteColor;
    cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    YBWeakSelf;
    cell.toolTextView = _commentTool.textField;
    cell.comCellEvent = ^{
        [weakSelf needLogin];
    };
    return cell;

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //return tableheader;
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //return 50;
    CGFloat headerH = 0.01;
    if (@available(iOS 13.0,*)) {
        headerH = 0;
    }
    return headerH;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    CGFloat footerH = 0.01;
    if (@available(iOS 13.0,*)) {
        footerH = 0;
    }
    return footerH;
}
//刷新评论数量
-(void)getNewCount:(int)counts{
     _allCommentLabels.text = [NSString stringWithFormat:@"%d %@",counts,YZMsg(@"评论")];
}
-(void)reloadcomments:(NSNotification *)ns{
    NSDictionary *subdicsss = [ns userInfo];
    //904
    BOOL isLike = NO;
    int numbers = 0;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (int i=0; i<_itemsarray.count; i++) {
        NSDictionary *subdic = _itemsarray[i];
        
        NSString *parentid = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"id"]];
        NSString *myparentid = [NSString stringWithFormat:@"%@",[subdicsss valueForKey:@"commentid"]];
        if ([parentid isEqual:myparentid]) {
            dic = [NSMutableDictionary dictionaryWithDictionary:subdic];
            numbers = i;
            isLike = YES;
            break;
        }
    }
    if (isLike == YES) {
        [_itemsarray removeObject:dic];
        [dic setObject:[subdicsss valueForKey:@"commentnums"] forKey:@"replys"];
        [_itemsarray insertObject:dic atIndex:(NSUInteger)numbers];
        [self.tableview reloadData];
    }
    
    
}
-(void)needLogin {
    [_commentTool.textField resignFirstResponder];
    self.youkedenglu(nil);
}
-(void)pushmessage:(NSString *)voiceKey{
    if ([[Config getOwnID] intValue] <= 0) {
        [self needLogin];
        return;
    }
    
    
    /*
     parentid  回复的评论ID
     commentid 回复的评论commentid
     touid     回复的评论UID
     如果只是评论 这三个传0
     */
    if (_commentTool.textField.text.length == 0 || _commentTool.textField.text == NULL || _commentTool.textField.text == nil || [_commentTool.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length == 0) {
        if ([PublicObj checkNull:voiceKey]) {
            [MBProgressHUD showPop:YZMsg(@"请添加内容后再尝试")];
            return;
        }
    }
     NSString *sendtouid = [NSString stringWithFormat:@"%@",_touid];
     NSString *sendcommentid = [NSString stringWithFormat:@"%@",_commentid];
     NSString *sendparentid = [NSString stringWithFormat:@"%@",_parentid];
     NSString *path = [NSString stringWithFormat:@"%@",_commentTool.textField.text];
    //隐藏
//    [self dissmiss];
    [self endEditing:YES];
    
    NSString *at_json = @"";
    //转json、去除空格、回车
    if (_commentTool.atArray.count>0) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_commentTool.atArray options:NSJSONWritingPrettyPrinted error:nil];
        at_json = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        at_json = [at_json stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        at_json = [at_json stringByReplacingOccurrencesOfString:@" " withString:@""];
        at_json = [at_json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    }
    /*
    NSString *url = [NSString stringWithFormat:@"Video.setComment&videoid=%@&content=%@&uid=%@&token=%@&touid=%@&commentid=%@&parentid=%@&at_info=%@&type=%@&voice=%@&length=%@",_videoid,[PublicObj checkNull:voiceKey]?path:@"",[Config getOwnID],[Config getOwnToken],sendtouid,sendcommentid,sendparentid,at_json,[PublicObj checkNull:voiceKey]?@"0":@"1",voiceKey,[PublicObj checkNull:voiceKey]?@"0":_commentTool.voiceDution];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    */
    NSString *url = @"Video.setComment";
    NSDictionary *postDic = @{@"videoid":_videoid,
                              @"content":[PublicObj checkNull:voiceKey]?path:@"",
                              @"touid":sendtouid,
                              @"commentid":sendcommentid,
                              @"parentid":sendparentid,
                              @"at_info":at_json,
                              @"type":[PublicObj checkNull:voiceKey]?@"0":@"1",
                              @"voice":voiceKey?voiceKey:@"",
                              @"length":[PublicObj checkNull:voiceKey]?@"0":_commentTool.voiceDution,
    };
    YBWeakSelf;
    
    [WYNetworking postWithUrl:url Dic:postDic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            
            _commentTool.textField.text = @"";
            _commentTool.textField.placeholder = YZMsg(@"说点什么吧~");
            //论完后 把状态清零
            _touid = _hostid;
            _parentid = @"0";
            _commentid = @"0";
            
            [MBProgressHUD showPop:YZMsg(@"评论成功")];
            [_commentTool.atArray removeAllObjects];
            NSDictionary *infoDic = [info firstObject];
            //刷新评论数
            int allcomments = [[NSString stringWithFormat:@"%@",[infoDic valueForKey:@"comments"]] intValue];
            weakSelf.allCommentLabels.text = [NSString stringWithFormat:@"%d %@",allcomments,YZMsg(@"评论")];
            self.talkCount([NSString stringWithFormat:@"%@",[infoDic valueForKey:@"comments"]] );
            
            if (isReply) {
                isReply = NO;
                //回复评论
                [_currentCell requestData:YES andBtn:_currentCell.model.replyMoreBtn];
            }else{
                //对视频评论
                count = 0;
                _needScroll = YES;
                [self reloaddata:_fromWhere];
            }
            
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}
#pragma mark -- 获取键盘高度
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //tabFrame = CGRectMake(0, _window_height*0.3+50, _window_width, _window_height*0.7 - 50-ShowDiff-50);
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.origin.y;
    //CGFloat yyyy = keyboardRect.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        //消息事件 tableview 全屏不处理frame
        if (![_fromWhere isEqual:@"消息事件"]) {
            //self.tableview.frame = CGRectMake(0, _window_height*0.3 + 50 - yyyy/2, _window_width, _window_height*0.7 - 84-statusbarHeight);
            /*9-17
             tableheader.y -= yyyy/2;
             _tableview.y -= yyyy/2;
             */
            /*11-16 键盘弹起不再改变 评论视图 的高度
             self.y = -yyyy/2;
             _commentTool.y = _window_height - 50 - yyyy/2;//-ShowDiff
             */
        }
        if(!isLandScreen){
            _commentTool.frame = CGRectMake(0, height - 50, _window_width, 50);
            _commentTool.emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
        }
    }];

}
- (void)keyboardWillHide:(NSNotification *)aNotification {
    //消息事件 tableview 全屏不处理frame
    if (![_fromWhere isEqual:@"消息事件"] && _isClickCloseBtn == NO) {
        //self.tableview.frame = CGRectMake(0, _window_height*0.3, _window_width, _window_height*0.7 - 50-ShowDiff);
        /*9-17
        tableheader.y = _window_height*0.3;
        _tableview.y = _window_height*0.3+50;
        */
        self.y = 0;
    }
    if(!isLandScreen){
        
        [UIView animateWithDuration:0.25 animations:^{
            _commentTool.frame = CGRectMake(0, _window_height - 50-ShowDiff, _window_width, 50+ShowDiff);
            _commentTool.emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
        }];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [_commentTool.textField resignFirstResponder];
}

#pragma mark cell代理方法
//这个地方找到点赞的字典，在数组中删除再重新插入 处理点赞
-(void)makeLikeRloadList:(NSString *)commectid andLikes:(NSString *)likes islike:(NSString *)islike{

    int numbers = 0;
    for (int i=0; i<_itemsarray.count; i++) {
        NSMutableDictionary *subdic = _itemsarray[i];
        NSString *parentid = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"id"]];
        if ([parentid isEqual:commectid]) {
            [subdic setObject:likes forKey:@"likes"];
            [subdic setObject:islike forKey:@"islike"];

            numbers = i;
            break;
        }
    }
    //[self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:numbers inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
-(void)reload:(NSNotification *)ns{
    NSDictionary *subdicsss = [ns userInfo];
    //904
    BOOL isLike = NO;
    int numbers = 0;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (int i=0; i<_itemsarray.count; i++) {
        NSDictionary *subdic = _itemsarray[i];
        NSString *parentid = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"id"]];
        NSString *myparentid = [NSString stringWithFormat:@"%@",[subdicsss valueForKey:@"commentid"]];
        if ([parentid isEqual:myparentid]) {
            dic = [NSMutableDictionary dictionaryWithDictionary:subdic];
            numbers = i;
            isLike = YES;
            break;
        }
    }
    if (isLike == YES) {
        [_itemsarray removeObject:dic];
        [dic setObject:[subdicsss valueForKey:@"likes"] forKey:@"likes"];
        [dic setObject:[subdicsss valueForKey:@"islike"] forKey:@"islike"];
        [_itemsarray insertObject:dic atIndex:(NSUInteger)numbers];
        [self.tableview reloadData];
    }
}
-(void)longPressing {
    [_commentTool.textField resignFirstResponder];
}
- (void)endEditOfGoHome {
    [self endEditing:YES];
}
-(void)endEnterCenter{
    [self dissmiss];
}
-(void)pushDetails:(NSDictionary *)commentdic andCell:(id)comcell{
    
    _currentCell = (commCell *)comcell;
    NSIndexPath *indexPath = [_tableview indexPathForCell:_currentCell];
    _needScorllToIndexPath = indexPath;
    
    NSDictionary *userinfo = [commentdic valueForKey:@"userinfo"];
    _touid = [NSString stringWithFormat:@"%@",[userinfo valueForKey:@"id"]];
    //20-6-28确定不能回复自己且不给提示
    if ([_touid isEqual:[Config getOwnID]]) {
        //[MBProgressHUD showPop:@"不能回复自己"];
        return;
    }
    if (_commentTool.voiceBtn.selected == NO) {
        [_commentTool.textField becomeFirstResponder];
    }
    NSString *path = [NSString stringWithFormat:@"%@:%@",YZMsg(@"回复给"),[userinfo valueForKey:@"user_nickname"]];
    _commentTool.textField.placeholder = path;
    _parentid = [NSString stringWithFormat:@"%@",[commentdic valueForKey:@"id"]];
    _commentid = [NSString stringWithFormat:@"%@",[commentdic valueForKey:@"commentid"]];
    isReply = YES;

}
- (void)playDetailesVoice:(detailmodel *)model andCell:(commDetailCell *)comcell{
    _isDetailPlay = YES;
    if (_voiceCell && _isPlaying) {
        _isPlaying = NO;
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_voicePlayer.currentItem];
        [_voicePlayer removeTimeObserver:self.playbackTimeObserver];
        [_voicePlayer removeObserver:self forKeyPath:@"status"];
        [_voicePlayer pause];
        _voicePlayer = nil;
        if (self.mutedBlock) {
            self.mutedBlock(@"0");
        }
        _voiceCell.animationView.hidden = YES;
        _voiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",_voiceCell.model.voiceTime];
        _voiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
    }
    if (_detailVoiceCell == comcell) {
        if (_isPlaying) {
            _isPlaying = NO;
            [_voicePlayer pause];
            if (self.mutedBlock) {
                self.mutedBlock(@"0");
            }
            _detailVoiceCell.animationView.hidden = YES;
            _detailVoiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",model.voiceTime];
            _detailVoiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
            return;
        }
    }else{
        _detailVoiceCell.animationView.hidden = YES;
        _detailVoiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",_detailVoiceCell.model.voiceTime];
        _detailVoiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
        
    }
//    if (self.mutedBlock) {
//        self.mutedBlock(@"1");
//    }
//    _isPlaying = NO;
    _detailVoiceCell = comcell;
    [self doplayWithModel:model];

}


- (void)playVoice:(commentModel *)model andCell:(id)comcell{
    
    _isDetailPlay = NO;

    if (_detailVoiceCell && _isPlaying) {
        _isPlaying = NO;
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_voicePlayer.currentItem];
        [_voicePlayer removeTimeObserver:self.playbackTimeObserver];
        [_voicePlayer removeObserver:self forKeyPath:@"status"];
        [_voicePlayer pause];
        _voicePlayer = nil;
        if (self.mutedBlock) {
            self.mutedBlock(@"0");
        }
        _detailVoiceCell.animationView.hidden = YES;
        _detailVoiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",model.voiceTime];
        _detailVoiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
    }

    
    if (_voiceCell == comcell) {
        if (_isPlaying) {
            _isPlaying = NO;
            [_voicePlayer pause];
            if (self.mutedBlock) {
                self.mutedBlock(@"0");
            }
            _voiceCell.animationView.hidden = YES;
            _voiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",model.voiceTime];
            _voiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
            return;
        }
    }else{
        _voiceCell.animationView.hidden = YES;
        _voiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",_voiceCell.model.voiceTime];
        _voiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];

    }
    _voiceCell = (commCell *)comcell;
    [self doplayWithModel:model];

}
- (void)doplayWithModel:(id)mod{
    NSString *timeStr;
    NSString *url;
    
    if (_isDetailPlay) {
        detailmodel *model = mod;
        timeStr = model.voiceTime;
        url = model.voiceUrl;
    }else{
        commentModel *model = mod;
        timeStr = model.voiceTime;
        url = model.voiceUrl;
    }
    if (self.mutedBlock) {
        self.mutedBlock(@"1");
    }
    _isPlaying = NO;
    int floattotal = [timeStr intValue];
    if (_voicePlayer) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_voicePlayer.currentItem];
        [_voicePlayer removeTimeObserver:self.playbackTimeObserver];
        [_voicePlayer removeObserver:self forKeyPath:@"status"];
        [_voicePlayer pause];
        _voicePlayer = nil;
        //        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:model.voiceUrl]];
        //        [_voicePlayer replaceCurrentItemWithPlayerItem:item];
    }else{
    }
//    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
//    _voicePlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    NSMutableDictionary * headers = [NSMutableDictionary dictionary];
    [headers setObject:h5url forKey:@"referer"];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:url] options:@{@"AVURLAssetHTTPHeaderFieldsKey" : headers}];
    // 初始化playerItem
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:urlAsset];
    _voicePlayer = [[AVPlayer alloc] initWithPlayerItem:item];

    [_voicePlayer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

    YBWeakSelf;
    _playbackTimeObserver = [_voicePlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, NSEC_PER_SEC) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //当前播放的时间
        CGFloat floatcurrent = CMTimeGetSeconds(time);
        NSLog(@"floatcurrent = %.1f",floatcurrent);
        //总时间
        if (weakSelf.isDetailPlay) {
            weakSelf.detailVoiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%.0f\"",(floattotal-floatcurrent) > 0 ? (floattotal-floatcurrent) : 0];
        }else{
            weakSelf.voiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%.0f\"",(floattotal-floatcurrent) > 0 ? (floattotal-floatcurrent) : 0];
        }
        
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
        //默认情况下扬声器播放
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [_voicePlayer play];
        _voicePlayer.volume = 1;
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_voicePlayer.currentItem];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status)
        {
                /* Indicates that the status of the player is not yet known because
                 it has not tried to load new media resources for playback */
            case AVPlayerStatusUnknown:
            {
                [MBProgressHUD showError:YZMsg(@"播放失败")];
                _isPlaying = NO;
                if (self.mutedBlock) {
                    self.mutedBlock(@"0");
                }

            }
                break;
                
            case AVPlayerStatusReadyToPlay:
            {
                //                [self creatJumpBtn];
                _isPlaying = YES;
                if (_isDetailPlay) {
                    _detailVoiceCell.animationView.hidden = NO;
                    _detailVoiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_play"];
                }else{
                    _voiceCell.animationView.hidden = NO;
                    _voiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_play"];
                }

            }
                break;
                
            case AVPlayerStatusFailed:
            {
                [MBProgressHUD showError:YZMsg(@"播放失败")];
                _isPlaying = NO;
                if (self.mutedBlock) {
                    self.mutedBlock(@"0");
                }

            }
                break;
        }
        
    }
    
}
- (void)playFinished:(NSNotification *)not{
    
    _isPlaying = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_voicePlayer.currentItem];
    [_voicePlayer removeTimeObserver:self.playbackTimeObserver];
    [_voicePlayer removeObserver:self forKeyPath:@"status"];
    [_voicePlayer pause];
    _voicePlayer = nil;

    if (_isDetailPlay) {
        _detailVoiceCell.animationView.hidden = YES;
        _detailVoiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",_detailVoiceCell.model.voiceTime];
        _detailVoiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];

    }else{
        _voiceCell.animationView.hidden = YES;
        _voiceCell.voiceTimeL.text = [NSString stringWithFormat:@"%@\"",_voiceCell.model.voiceTime];
        _voiceCell.voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
    }
    if (self.mutedBlock) {
        self.mutedBlock(@"0");
    }
    
}
- (void)appDidEnterBackground:(NSNotification *)not{
    if (_voicePlayer) {
        [_voicePlayer pause];
        [self playFinished:not];
    }

}

//- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;

- (YBCommentToolBar *)commentTool {
    YBWeakSelf;
    if (!_commentTool) {
        _commentTool = [[YBCommentToolBar alloc]initWithFrame:CGRectMake(0,_window_height - 50-ShowDiff, _window_width, 50+ShowDiff) andVCType:1 superView:self];
        _commentTool.backgroundColor = UIColor.whiteColor;
        
        //_toolBar顶部横线 和 顶部 view分割开
        UILabel *lineso = [[UILabel alloc]initWithFrame:CGRectMake(0,0,_window_width,1)];
        lineso.backgroundColor = RGB(235, 235, 235);
        [_commentTool addSubview:lineso];
                
        _commentTool.comToolEvent = ^(NSString *eventType, NSDictionary *eventDic) {
            [weakSelf commentToolCallBack:eventType andEventDic:eventDic];
        };
    }
    return _commentTool;
}
-(void)commentToolCallBack:(NSString *)eventType andEventDic:(NSDictionary *)eventDic {
    if ([eventType isEqual:@"工具-游客"]) {
        [self needLogin];
    }
    if ([eventType isEqual:@"工具-录音"]) {
        //录音的时候，直接暂停播放
        NSString *mutedtype = minstr([eventDic valueForKey:@"mutedType"]);
        if ([mutedtype isEqual:@"1"]) {
            [self playFinished:nil];
        }
        
        if (self.mutedBlock) {
            self.mutedBlock(minstr([eventDic valueForKey:@"mutedType"]));
        }
    }
    if ([eventType isEqual:@"工具-发送消息"]) {
        NSString *voiceKey = minstr([eventDic valueForKey:@"voiceKey"]);
        [self pushmessage:voiceKey];
    }
}


@end
